package com.hrm.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.hrm.domain.Dept;
import com.hrm.domain.EmpExt;
import com.hrm.domain.Employee;
import com.hrm.domain.JSONEmpExtResult;
import com.hrm.domain.Job;
import com.hrm.domain.PageHelper;
import com.hrm.service.DeptService;
import com.hrm.service.EmployeeService;
import com.hrm.service.JobService;
import com.hrm.service.Impl.DeptServiceImpl;
import com.hrm.service.Impl.EmployeeServiceImpl;
import com.hrm.service.Impl.JobServiceImpl;

/*
 * 部门数据控制层
 */
@WebServlet(urlPatterns = { "/getEmps", "/addEmp", "/delEmp", "/delEmps", "/modifyEmp" })
@SuppressWarnings("all") // 使用注解抑制警告信息
public class EmployeeController extends HttpServlet {

	// 定义全局变量
	private EmployeeService es = new EmployeeServiceImpl(); // CURD员工数据
	private DeptService ds = new DeptServiceImpl(); // CURD部门数据
	private JobService js = new JobServiceImpl(); // CURD职位数据

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String url = request.getRequestURI(); // 获取跳转路径
		// 进行截取并判断
		String operator = url.substring(url.lastIndexOf("/") + 1);
		if ("getEmps".equals(operator)) { // 分页查询 + 模糊
			getEmps(request, response);
		} else if ("addEmp".equals(operator)) { // 添加员工
			addEmp(request, response);
		} else if ("delEmp".equals(operator)) { // 删除指定员工
			delEmp(request, response);
		} else if ("delEmps".equals(operator)) { // 删除多个员工
			delEmps(request, response);
		} else if ("modifyEmp".equals(operator)) { // 修改指定员工的信息
			modifyEmp(request, response);
		}
	}

	// 分页查询 + 模糊
	private void getEmps(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PageHelper ph = new PageHelper(); // 简化分页查询
		List<EmpExt> emps = new ArrayList<>(); // 用于存储查询到的数据
		int count = 0; // 用于记录数据条数
		HashSet<Integer> flag = new HashSet(); // 用于判断情况
		String empName = request.getParameter("ename");
		String empCard = request.getParameter("ecard");
		String empPhone = request.getParameter("ephone");
		String dept = request.getParameter("edept");
		String job = request.getParameter("ejob");
		String sex = request.getParameter("esex");
		int empDept = Integer.parseInt(dept.replaceAll(" ", ""));
		int empJob = Integer.parseInt(job.replaceAll(" ", ""));
		int empSex = Integer.parseInt(sex.replaceAll(" ", ""));
		// 获取所有职位和部门的信息
		List<Job> jobs = js.getAllJob();
		List<Dept> depts = ds.getAllDept();
		if (empName == "" && empCard == "" && empPhone == "" && empDept == 0 && empJob == 0 && empSex == 0) { // 没有查询条件
			flag.add(1);
		}
		// 获取查询出的数据记录数,并设置模糊查询
		if(!flag.contains(1)) {
			empName = "'%" + empName + "%'";
			empCard = "'%" + empCard + "%'";
			empPhone = "'%" + empPhone + "%'";
		}
		if (empSex != 0) {// 有性别
			flag.add(2);
		}
		if (empJob != 0) { // 有职位
			flag.add(3);
		}
		if (empDept != 0) { // 有部门
			flag.add(4);
		}
		if (flag.contains(1)) {
			count = es.getCount(flag);
		} else {
			count = es.getCount(flag, empName, empCard, empPhone, empSex, empJob, empDept);
		}
		ph.setPageIndex(1); // 设置当前页的初始数据
		// 获取当前页
		String pageNo = request.getParameter("pageNo");
		if (pageNo != null) { // 说明点了页码
			ph.setPageIndex(Integer.parseInt(pageNo)); // 重新设置页码
			ph.setTotalPageSum(ph.getTotalPageSum()); // 重新设置总页数
		}
		ph.setPageSize(ph.getPageSize()); // 设置每页显示的记录条数
		ph.setTotalRecordSum(count); // 设置总记录条数
		// 获取当前页的数据
		if (flag.contains(1)) {
			emps = es.getEmpExtsByTerm(flag, ph.getStartRowNum(), ph.getPageSize());
		} else { // 有查询条件
			emps = es.getEmpExtsByTerm(flag, empName, empCard, empPhone, empSex, empJob, empDept, ph.getStartRowNum(),
					ph.getPageSize());
		}
		ph.setTotalPageSum(ph.getTotalPageSum()); // 设置总页数
		// 将查询到的数据转化为json
		JSONEmpExtResult aur = new JSONEmpExtResult();
		aur.setList(emps);
		aur.setPh(ph);
		if (emps != null && emps.size() > 0) {
			aur.setMsg("success");
			aur.setJobs(jobs);
			aur.setDepts(depts);
		}
		// 把aur对象转换成json数据
		String JobsJson = JSON.toJSONString(aur);
		// 把结果响应给客户端
		PrintWriter out = response.getWriter();
		out.write(JobsJson);
		out.flush();
		out.close();
	}

	// 添加员工
	private void addEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取前台传递的参数
		String empName = request.getParameter("ename");
		int empSex = Integer.parseInt(request.getParameter("esex"));
		String empCard = request.getParameter("ecard");
		String empPhone = request.getParameter("ephone");
		String empAddress = request.getParameter("eaddress");
		String empEdu = request.getParameter("eedu");
		String empSpec = request.getParameter("espec");
		String empJob = request.getParameter("ejob");
		String empDept = request.getParameter("edept");
		String msg = ""; // 定义返回消息
		// 多种判断,防止异常
		if (empName != "" && empCard != "" && empPhone != "" && empAddress != "" && empEdu != "" && empSpec != ""
				&& empJob != "" && empDept != "" && empSex != 0) {
			// 判断身份证是否重复
			Employee e1 = es.getEmpByCard(empCard);
			if (e1 == null) {
				// 判断职位是否存在
				Job j = js.getJobByJN(empJob);
				if (j != null) {
					// 判断部门是否存在
					Dept d = ds.getDeptByDN(empDept);
					if (d != null) {
						// 执行添加
						Employee newEmp = new Employee(d.getDeptID(), j.getjID(), empName, empCard, empAddress,
								empPhone, empSex, empEdu, empSpec);
						es.addEmp(newEmp);
					} else { // 部门不存在
						msg = "fd";
					}
				} else { // 职位不存在
					msg = "fj";
				}
			} else { // 身份证重复
				msg = "rc";
			}
		} else {
			msg = "fail"; // 存在空数据
		}
		// 将返回信息封装
		JSONEmpExtResult aur = new JSONEmpExtResult();
		aur.setMsg(msg);
		// 把aur对象转换成json数据
		String mJSON = JSON.toJSONString(aur);
		// 把结果响应给客户端
		PrintWriter out = response.getWriter();
		out.write(mJSON);
		out.flush();
		out.close();
	}

	// 删除员工
	private void delEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取前台传递的参数
		int empID = Integer.parseInt(request.getParameter("eid"));
		// 删除指定用户
		String msg = "success"; // 定义返回信息
		// 删除
		es.delEmp(empID);
		// 将返回信息封装
		JSONEmpExtResult aur = new JSONEmpExtResult();
		aur.setMsg(msg);
		// 把aur对象转换成json数据
		String mJSON = JSON.toJSONString(aur);
		// 把结果响应给客户端
		PrintWriter out = response.getWriter();
		out.write(mJSON);
		out.flush();
		out.close();
	}

	// 删除多个员工
	private void delEmps(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取前台传过来的数据
		String empsJSON = request.getParameter("emps");
		// 将JSON数组转换为集合
		List<String> emps = JSON.parseArray(empsJSON, String.class);
		String msg = ""; // 定义返回信息
		// 循环删除
		for (int i = 0; i < emps.size(); i++) {
			String empID = emps.get(i).replaceAll(" ", "");
			es.delEmp(Integer.parseInt(empID));
		}
		msg = "success";
		// 将返回信息封装
		JSONEmpExtResult aur = new JSONEmpExtResult();
		aur.setMsg(msg);
		// 把aur对象转换成json数据
		String mJSON = JSON.toJSONString(aur);
		// 把结果响应给客户端
		PrintWriter out = response.getWriter();
		out.write(mJSON);
		out.flush();
		out.close();
	}

	// 修改指定员工的信息
	private void modifyEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取前台传递的参数
		int empID = Integer.parseInt(request.getParameter("id"));
		String empName = request.getParameter("name");
		int empSex = Integer.parseInt(request.getParameter("sex"));
		String empCard = request.getParameter("card");
		String empPhone = request.getParameter("phone");
		String empAddress = request.getParameter("address");
		String empEdu = request.getParameter("edu");
		String empSpec = request.getParameter("spec");
		String empJob = request.getParameter("job");
		String empDept = request.getParameter("dept");
		String msg = ""; // 定义返回消息
		// 多种判断,防止异常
		if (empName != "" && empCard != "" && empPhone != "" && empAddress != "" && empEdu != "" && empSpec != ""
				&& empJob != "" && empDept != "" && empSex != 0) {
			// 判断身份证是否重复
			Employee e1 = es.getEmpByCard(empCard);
			if (e1 == null) {
				// 判断职位是否存在
				Job j = js.getJobByJN(empJob);
				if (j != null) {
					// 判断部门是否存在
					Dept d = ds.getDeptByDN(empDept);
					if (d != null) {
						// 执行添加
						Employee newEmp = new Employee(d.getDeptID(), j.getjID(), empName, empCard, empAddress,
								empPhone, empSex, empEdu, empSpec);
						es.modifyEmpByID(newEmp, empID);
					} else { // 部门不存在
						msg = "fd";
					}
				} else { // 职位不存在
					msg = "fj";
				}
			} else { // 身份证重复
				msg = "rc";
			}
		} else {
			msg = "fail"; // 存在空数据
		}
		// 将返回信息封装
		JSONEmpExtResult aur = new JSONEmpExtResult();
		aur.setMsg(msg);
		// 把aur对象转换成json数据
		String mJSON = JSON.toJSONString(aur);
		// 把结果响应给客户端
		PrintWriter out = response.getWriter();
		out.write(mJSON);
		out.flush();
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
